/*
 * @Author: Eli.Chen
 * @Date: 2025-04-29 17:42:21
 * @LastEditors: Eli.Chen
 * @LastEditTime: 2025-04-30 17:40:27
 * @Description:
 */

import React, { useState, useEffect } from 'react';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { Card, List, Button, Tag, message, Modal, Form, Input } from 'antd';
import { LockOutlined, MailOutlined, LogoutOutlined } from '@ant-design/icons';

import ForPasDialog from '@/components/user/ForPasDialog';
import EditEmailDialog from '@/components/user/EditEmailDialog';
import { checkSecurityInfo } from '@/api/user';
import { forgetPassword, logout } from '@/api/auth';
import { updateSecurityEmail } from '@/api/user';
import { storage } from '@/utils';

const UserSetting = () => {
    const navigate = useNavigate();
    const [password, setPassword] = useState({ isSet: false, value: '' });
    const [email, setEmail] = useState({ isSet: false, value: '' });
    const [isForOpen, setIsForOpen] = useState(false);
    const [isEmailOpen, setIsEmailOpen] = useState(false);
    const { userInfo } = useSelector((state) => state.auth);

    const handlePassword = (values) => {
        console.log(values);
        const reqParams = {
            email: userInfo?.email,
            password: values?.password,
            code: values?.captcha,
        };
        forgetPassword(reqParams).then((res) => {
            if (res.code === 200) {
                message.success(password.isSet ? '密码修改成功' : '密码设置成功');
                setIsForOpen(false);
            }
        });
    };

    // 新增修改邮箱逻辑
    const handleEmail = (values) => {
        const reqParams = {
            email: values?.email,
            code: values?.captcha,
        };
        updateSecurityEmail(reqParams).then((res) => {
            if (res.code === 400) {
                message.error(res.message);
                return;
            }
            if (res.code === 200) {
                message.success(email.isSet ? '邮箱修改成功' : '邮箱绑定成功');
                setIsEmailOpen(false);
            }
        });
    };

    const handleLogout = () => {
        logout().then(() => {
            storage.clearAuthStorage();
            navigate('/');
            message.success('已退出登录！');
            window.location.reload();
        });
    };

    const settings = [
        {
            title: '账户密码',
            icon: <LockOutlined />,
            status: password.isSet ? <Tag color="success">已设置</Tag> : <Tag color="error">存在风险，请设置密码</Tag>,
            action: (
                <Button type="link" onClick={() => setIsForOpen(true)}>
                    {password.isSet ? '修改密码' : '设置密码'}
                </Button>
            ),
        },
        {
            title: '安全邮箱',
            icon: <MailOutlined />,
            status: email.isSet ? (
                // <Tag color="success">已绑定（{email.value}）</Tag>
                <Tag color="success">已绑定</Tag>
            ) : (
                <Tag color="error">存在风险，请绑定邮箱</Tag>
            ),
            action: (
                <Button type="link" onClick={() => setIsEmailOpen(true)}>
                    {email.isSet ? '修改邮箱' : '绑定邮箱'}
                </Button>
            ),
        },
    ];

    const getSecurityInfo = async () => {
        try {
            const res = await checkSecurityInfo();
            if (res.code === 200) {
                setPassword({ ...password, isSet: res?.data.password });
                setEmail({ ...email, isSet: res?.data.email });
            }
        } catch (error) {
            console.error('Error fetching posts:', error);
        }
    };

    useEffect(() => {
        getSecurityInfo();
    }, []);

    return (
        <>
            <Card
                title="账号安全设置"
                bordered={false}
                style={{ background: 'none', boxShadow: 'none' }}
                bodyStyle={{ padding: 0 }}
            >
                <List
                    itemLayout="horizontal"
                    dataSource={settings}
                    renderItem={(item, index) => (
                        <List.Item
                            actions={[item.action]}
                            style={{
                                padding: '16px 0',
                                borderBottom: '1px solid #f0f0f0',
                                borderTop: 'none',
                            }}
                        >
                            <List.Item.Meta avatar={item.icon} title={item.title} description={item.status} />
                        </List.Item>
                    )}
                />
                <Button
                    type="link"
                    danger
                    icon={<LogoutOutlined />}
                    onClick={handleLogout}
                    block
                    style={{
                        marginTop: 24,
                        height: 40,
                        border: '1px solid #f0f0f0',
                        backgroundColor: 'transparent',
                    }}
                >
                    安全退出账号
                </Button>
            </Card>
            <ForPasDialog open={isForOpen} onOk={handlePassword} onCancel={() => setIsForOpen(false)} />
            <EditEmailDialog open={isEmailOpen} onOk={handleEmail} onCancel={() => setIsEmailOpen(false)} />
        </>
    );
};

export default UserSetting;
